import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

public class MainFrame extends JFrame{
	private static final long serialVersionUID = 1L;
	private ScrollPane panB;
	private JTable table;
	private int rmbNum = 0;

	public MainFrame (List<User> userList){
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				dispose();
				Launcher.writeUsers();
			}
		});
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
		setBounds(100,100,700,700);
		getContentPane().setLayout(null);

		panB=new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
		table = new JTable();
		Object[][] objectArray = getObjects(userList);
		table.setModel(new DefaultTableModel(
			objectArray,
			new String[] {
				"\u59D3\u540D", "\u79EF\u5206", "\u5269\u4F59\u79EF\u5206", "\u5355/\u53CC", "\u5927/\u5C0F", "\u5927\u5355", "\u5927\u53CC", "\u5C0F\u5355", "\u5C0F\u53CC", "\u5355\u70B9"
			}
		));
		table.setRowHeight(20);
		table.setBounds(0,0,700,700);
		fitTableColumns(table);
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer(){
			private static final long serialVersionUID = 1L;
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
				if(row < rmbNum){
					setBackground(new Color(184,207,229));
				}else{
					setBackground(Color.white);
				}
				return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			}
		};
		for(int i = 0; i < table.getColumnCount(); i++){
			table.getColumn(table.getColumnName(i)).setCellRenderer(tcr);
		}
		panB.add(new JScrollPane(table));
		panB.setBounds(0,0,700,600);
		getContentPane().add(panB);
		
		JButton buttonShowAddUser = new JButton("添加用户");
		buttonShowAddUser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new AddUserFrame();
				dispose();
			}
		});
		buttonShowAddUser.setFont(new Font("Dialog", Font.BOLD, 12));
		buttonShowAddUser.setBounds(12, 624, 86, 25);
		getContentPane().add(buttonShowAddUser);
		
		JButton buttonLottery = new JButton("开奖");
		buttonLottery.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String str = JOptionPane.showInputDialog(null,"请输入开奖结果","开奖",JOptionPane.QUESTION_MESSAGE);
				if(str != null && str.length() > 0){
					int result = Integer.valueOf(str);
					Launcher.getBettingResult(result);
					dispose();
					Launcher.showMainFrame();
				}
			}
		});
		buttonLottery.setFont(new Font("Dialog", Font.BOLD, 12));
		buttonLottery.setBounds(500, 624, 69, 25);
		getContentPane().add(buttonLottery);
		
		JButton buttonBetting = new JButton("投注");
		buttonBetting.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Launcher.showBettingFrame();
				dispose();
			}
		});
		buttonBetting.setFont(new Font("Dialog", Font.BOLD, 12));
		buttonBetting.setBounds(375, 624, 69, 25);
		getContentPane().add(buttonBetting);
		
		JButton buttonDeleteUser = new JButton("删除用户");
		buttonDeleteUser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
				Launcher.showDeleteUserFrame();
			}
		});
		buttonDeleteUser.setBounds(132, 624, 86, 25);
		getContentPane().add(buttonDeleteUser);
		
		JButton buttonModifyPoints = new JButton("修改积分");
		buttonModifyPoints.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
				Launcher.showModifyFrame();
			}
		});
		buttonModifyPoints.setBounds(248, 624, 86, 25);
		getContentPane().add(buttonModifyPoints);
		setResizable(false);
		setVisible(true);
	} 
	private void getObject(Object[] objectArray,User user){
		objectArray[0] = user.getName();
		objectArray[1] = user.getPoints();
		objectArray[2] = user.getRestPoints();
		if(user.getSubNum() > 0){
			objectArray[2] += "[+" + user.getAddNum() + " -" + user.getSubNum() + "]";
		}
		objectArray[3] = "";
		if(user.getSinglePoints() > 0){
			objectArray[3] = "单: " + user.getSinglePoints();
		}
		if(user.getDoublePoints() > 0){
			objectArray[3] += "双: " + user.getDoublePoints();
		}
		if(objectArray[3] == ""){
			objectArray[3] = "0";
		}
		objectArray[4] = "";
		if(user.getBigPoints() > 0){
			objectArray[4] = "大: " + user.getBigPoints();
		}else if(user.getSmallPoints() > 0){
			objectArray[4] += "小: " + user.getSmallPoints();
		}
		if(objectArray[4] == ""){
			objectArray[4] = "0";
		}
		objectArray[5] = "大单: " + user.getBigSinglePoints();
		objectArray[6] = "大双: " + user.getBigDoublePoints();
		objectArray[7] = "小单: " + user.getSmallSinglePoints();
		objectArray[8] = "小双: " + user.getSmallDoublePoints();
		int[] eachPoints = user.getEachPoints();
		String value = "";
		for(int j =0; j < User.NUM; j++){
			if(eachPoints[j] > 0){
				value += j + ": " + eachPoints[j] + "; ";
			}
		}
		if("".equals(value)){
			objectArray[9] = 0 + "";
		}else{
			objectArray[9] = value;
		}
	}

	private Object[][] getObjects(List<User> userList){
		Object[][] objectsArray = new Object[userList.size()][10];
		int index = 0;
		Iterator<User> ite = userList.iterator();
		while(ite.hasNext()){
			User user = ite.next();
			if(user.getType() == 1){
				getObject(objectsArray[index],user);
				index++;
			}
		}
		rmbNum = index;
		ite = userList.iterator();
		while(ite.hasNext()){
			User user = ite.next();
			if(user.getType() == 0){
				getObject(objectsArray[index],user);
				index++;
			}
		}
		assert(index == userList.size());
		return objectsArray;
	}
	
	/**
	 * resize table column size with contents
	 * @param myTable
	 */
	 public void fitTableColumns(JTable myTable){
		 myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         JTableHeader header = myTable.getTableHeader();
         int rowCount = myTable.getRowCount();
         Enumeration<TableColumn> columns = myTable.getColumnModel().getColumns();
         while(columns.hasMoreElements()) {
        	 TableColumn column = (TableColumn)columns.nextElement();
             int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
             int width = (int)header.getDefaultRenderer().getTableCellRendererComponent
            		 (myTable, column.getIdentifier(), false, false, -1, col).getPreferredSize().getWidth();
             for(int row = 0; row < rowCount; row++){
            	 int preferedWidth = (int)myTable.getCellRenderer(row, col).getTableCellRendererComponent
            			 (myTable, myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
                 width = Math.max(width, preferedWidth);
             }
             header.setResizingColumn(column); // 此行很重要
             column.setWidth(width+myTable.getIntercellSpacing().width);
          }
     }
}
